<template>
  <div class="orders-container">
    <!-- 搜索卡片 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" size="medium" @submit.native.prevent>
        <!-- 订单编号 -->
        <el-form-item label="订单编号">
          <el-input
            v-model="param.orderId"
            placeholder="输入订单编号"
            clearable
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>

        <!-- 支付方式 -->
        <el-form-item label="支付方式">
          <el-select
            v-model="param.paymentMethodId"
            placeholder="全部支付方式"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in param.paymentMethodList"
              :key="item.paymentMethodId"
              :label="item.paymentMethodName"
              :value="item.paymentMethodId"
            />
          </el-select>
        </el-form-item>

        <!-- 订单状态 -->
        <el-form-item label="订单状态">
          <el-select
            v-model="param.statusId"
            placeholder="全部状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in param.statusList"
              :key="item.statusId"
              :label="item.statusName"
              :value="item.statusId"
            />
          </el-select>
        </el-form-item>

        <!-- 时间范围 -->
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="param.orderDate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 380px"
          />
        </el-form-item>

        <!-- 金额范围 -->
        <el-form-item label="金额范围">
          <el-input-number
            v-model="param.actualAmountMin"
            :min="0"
            controls-position="right"
            placeholder="最低金额"
            style="width: 120px"
          />
          <span class="range-separator">-</span>
          <el-input-number
            v-model="param.actualAmountMax"
            :min="param.actualAmountMin || 0"
            controls-position="right"
            placeholder="最高金额"
            style="width: 120px"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button
            type="primary"
            icon="el-icon-search"
            :disabled="searchLoading"
            :loading="searchLoading"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <div class="total-tip">查询结果：共 {{ total }} 条记录</div>

      <el-table
        :data="orderList"
        v-loading="loading"
        element-loading-text="数据加载中..."
        element-loading-spinner="el-icon-loading"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
      >
        <el-table-column
          prop="orderId"
          label="订单编号"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="下单时间"
          width="180"
          align="center"
        />
        <el-table-column
          prop="paymentMethodName"
          label="支付方式"
          width="120"
          align="center"
        />
        <el-table-column
          prop="totalAmount"
          label="商品金额"
          width="120"
          align="right"
        >
          <template slot-scope="scope">
            ￥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="deliveryFee"
          label="配送费"
          width="100"
          align="right"
        >
          <template slot-scope="scope">
            ￥{{ scope.row.deliveryFee.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="actualAmount"
          label="实付金额"
          width="120"
          align="right"
        >
          <template slot-scope="scope">
            <span class="amount-text">
              ￥{{ scope.row.actualAmount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="quantity"
          label="商品数量"
          width="100"
          align="center"
        />
        <el-table-column label="收货地址" width="120" align="center">
          <template slot-scope="scope">
            <el-popover
              placement="top-start"
              width="200"
              trigger="hover"
            >
              <p class="address-popover">{{ scope.row.address }}</p>
              <el-button
                slot="reference"
                type="text"
                style="color: #409eff"
              >
                查看地址
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="statusName"
          label="订单状态"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getStatusTagType(scope.row.statusId)"
              effect="plain"
            >
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleOrderDetail(scope.row.orderId)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        :current-page.sync="pageParam.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size.sync="pageParam.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination-container"
      />
    </el-card>
  </div>
</template>

<script>
// 防抖函数
const debounce = (func, wait = 800) => {
  let timeout
  return function (...args) {
    const context = this
    return new Promise((resolve) => {  // 返回Promise
      clearTimeout(timeout)
      timeout = setTimeout(async () => {
        const result = await func.apply(context, args)
        resolve(result)  // 传递结果
      }, wait)
    })
  }
}

export default {
  name: 'Orders',
  data() {
    return {
      loading: false,
      searchLoading: false,
      param: {
        orderId: '',
        paymentMethodId: '',
        statusId: '',
        orderDate: [],
        actualAmountMin: null,
        actualAmountMax: null,
        totalAmountMin: null,
        totalAmountMax: null,
        quantityMin: null,
        quantityMax: null,
        statusList: [],
        paymentMethodList: []
      },
      orderList: [],
      total: 0,
      pageParam: {
        pageNum: 1,
        pageSize: 10,
        param: {}
      },
      cancelToken: null
    }
  },
  created() {
    this.debouncedQuery = debounce(this.queryOrderByCondition, 300)
    this.debouncedPageChange = debounce(this.handlePageChange, 300)
    this.initData()
  },
  methods: {
    // 初始化数据
    async initData() {
      await Promise.all([
        this.getPaymentMethodList(),
        this.getOrderStatusList()
      ])
      this.queryOrderByCondition()
    },

    // 获取支付方式
    async getPaymentMethodList() {
      try {
        const res = await this.$axios.get('api/order/queryPaymentMethodList')
        if (res.data.code === 200) {
          this.param.paymentMethodList = res.data.data
        }
      } catch (error) {
        console.error('支付方式加载失败', error)
      }
    },

    // 获取订单状态
    async getOrderStatusList() {
      try {
        const res = await this.$axios.get('api/order/queryStatusList')
        if (res.data.code === 200) {
          this.param.statusList = res.data.data
        }
      } catch (error) {
        console.error('订单状态加载失败', error)
      }
    },

    // 查询处理
    handleSearch() {
      this.searchLoading = true
      this.debouncedQuery()
        .catch(error => {
          console.error('查询错误:', error)
        })
        .finally(() => {
          this.searchLoading = false  // 确保状态重置
        })
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageParam.pageSize = val
      this.debouncedPageChange()
    },

    handleCurrentChange(val) {
      this.pageParam.pageNum = val
      this.debouncedPageChange()
    },

    handlePageChange() {
      this.queryOrderByCondition()
    },

    // 核心查询方法
    async queryOrderByCondition() {
      if (this.cancelToken) {
        this.cancelToken.cancel('取消重复请求')
      }
      this.cancelToken = this.$axios.CancelToken.source()

      this.loading = true
      try {
        const params = {
          pageNum: this.pageParam.pageNum,
          pageSize: this.pageParam.pageSize,
          param: {
            // 确保参数正确性
            orderId: this.param.orderId.trim(),
            paymentMethodId: this.param.paymentMethodId,
            statusId: this.param.statusId,
            createTimeMin: this.param.orderDate?.[0] || '',
            createTimeMax: this.param.orderDate?.[1] || '',
            actualAmountMin: this.param.actualAmountMin ?? undefined,
            actualAmountMax: this.param.actualAmountMax ?? undefined
          }
        }

        const res = await this.$axios.post('api/order/queryOrderByCondition', params, {
          cancelToken: this.cancelToken.token
        })
        if (res.data.code === 200) {
          this.orderList = res.data.data?.list || []
          this.total = res.data.data?.total || 0
        } else {
          this.$message.error(`查询失败: ${res.data.msg}`)
        }
      } catch (error) {
        if (!this.$axios.isCancel(error)) {
          // 处理真实错误
          this.$message.error('网络请求异常')
        }
      } finally {
        this.loading = false
      }
    },

    // 状态标签样式
    getStatusTagType(statusId) {
      const map = {
        1: 'info',    // 待支付
        2: 'success', // 已支付
        3: '',        // 已分拣
        4: 'warning', // 配送中
        5: 'success', // 已完成
        6: 'danger'   // 已取消
      }
      return map[statusId] || 'info'
    },

    // 重置查询
    resetQuery() {
      this.param = {
        ...this.param,
        orderId: '',
        paymentMethodId: '',
        statusId: '',
        orderDate: [],
        actualAmountMin: null,
        actualAmountMax: null,
        totalAmountMin: null,
        totalAmountMax: null,
        quantityMin: null,
        quantityMax: null
      }
      this.pageParam.pageNum = 1
      this.queryOrderByCondition()
    },

    // 查看详情
    handleOrderDetail(orderId) {
      this.$router.push({
        path: '/orderItem',
        query: { orderId }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.orders-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
    ::v-deep .el-card__body {
      padding: 20px;
    }

    .el-form-item {
      margin-right: 30px;
      margin-bottom: 10px;
    }

    .range-separator {
      margin: 0 10px;
      color: #909399;
    }

    .form-actions {
      float: right;
    }
  }

  .table-card {
    ::v-deep .el-card__body {
      padding: 0;
    }

    .total-tip {
      padding: 16px;
      color: #606266;
      border-bottom: 1px solid #ebeef5;
    }

    .amount-text {
      font-weight: 600;
      color: #f56c6c;
    }

    .address-popover {
      margin: 0;
      line-height: 1.6;
      word-break: break-all;
    }
  }

  .pagination-container {
    padding: 20px;
    text-align: right;
  }
}
</style>